When we add a component, such as a JLabel or JTextField to another component like a JPanel, then it needs to know how to lay it out on the screen. By default a JFrame uses something called BorderLayout and a JPanel used FlowLayout.
If we place a component in the center then it will stretch to fill the area and grow and shrink as the window is resized. If we put a component in north or south then it will retain a fixed height but grow horizontally. East and West retain a fixed width but grow vertically alongside center.
We do not have to use all of the locations. We might put something in center and then two JButtons, OK and CANCEL in South. Or we might use the BorderLayout just to hold a JLabel in West and a JTextField in Center. This can then be a inserted into another parent layout manager. It is very common to nest layouts to get the effect we want.
We set up a BorderLayout and use it like this:
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
JLable lab = new JLabel("Callsign");
JTextField field = new JTextField();
panel1.add(lab, BorderLayout.WEST);
panel1.add(field, BorderLauout.CENTER);
As you might expect, there are numerous settings to tweak the layout, such as spacing, but this is enough for an introduction.
Flow layout is the default for most components, including JPanels. If we add two components then they are flowed left to right. We can change that to be vertical if we want. It's useful in many situations, usually on sub panels in a window.
Copyright 2001-2021 Chris Thompson
Send me an email